package com.xsf.pay.common.inteceptor;

import cn.hutool.core.util.StrUtil;
import com.xsf.pay.common.constants.RedisConstant;
import com.xsf.pay.common.exception.BusinessRunTimeException;
import com.xsf.pay.service.RedisService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 登陆信息拦截器
 *
 * @author Administrator
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private RedisService redisService;
//    @Resource
//    private QggUserService qggUserService;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            // 获取用户详细信息
            Object principal = authentication.getPrincipal();

            if (principal instanceof UserDetails userDetails) {
                if (!redisService.hasKey(StrUtil.format(RedisConstant.ACCESS_TOKEN_CACHE, userDetails.getUsername()))) {
                    throw new BusinessRunTimeException(401, "用户信息已过期，请重新登录");
                }
                // todo 设置登录信息
//                QggUser qggUser = qggUserService.getOne(new LambdaQueryWrapper<QggUser>()
//                        .eq(QggUser::getUserName, userDetails.getUsername())
//                        .eq(QggUser::getDeleteFlag, DelFlagEnum.UNDELETED.getCode()));
//                request.setAttribute(BusinessConstants.SYS_USER, qggUser);
//                UserContext.removeUser();
//                UserContext.setUser(qggUser);
            }
        } else {
            throw new BusinessRunTimeException(401, "用户信息已过期，请重新登录");
        }
        return true;
    }
}
